/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import { isURL } from '@/utils/validate'
import { clearLoginInfo } from '@/utils'

Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  { path: '/404', component: _import('common/404'), name: '404', meta: { title: '404未找到' } },
  { path: '/register', component: _import('common/register'), name: 'register', meta: { title: '注册' } },
  { path: '/login', component: _import('common/login'), name: 'login', meta: { title: '登录' } },
  { path: '/healthy_report', component: _import('common/healthy_report'), name: 'login', meta: { title: '健康报告' } }
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: _import('main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口整体布局' },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    { path: '/home', component: _import('common/home'), name: 'home', meta: { title: '系统首页' } },
    // 不及格
    { path: '/fail', component: _import('common/fail'), name: 'fail', meta: { title: '不及格名单', isTab: true } },
    { path: '/theme', component: _import('common/theme'), name: 'theme', meta: { title: '主题' } },
    { path: '/demo-echarts', component: _import('demo/echarts'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
    { path: '/demo-ueditor', component: _import('demo/ueditor'), name: 'demo-ueditor', meta: { title: 'demo-ueditor', isTab: true } },
    // 作业管理-作业详情
    { path: '/enterinfor', component: _import('alone/enterinfor'), name: 'enterinfor', meta: { title: '作业详情', isTab: true } },
    // 作业管理-作业详情-布置作业
    { path: '/assignment', component: _import('alone/assignment'), name: 'assignment', meta: { title: '作业详情-布置作业', isTab: true } },
    // 作业管理-作业详情-个人
    { path: '/workPerDet', component: _import('alone/workPerDet'), name: 'workPerDet', meta: { title: '作业详情-个人', isTab: true } },
    // 课程管理-新增
    { path: '/dealer', component: _import('alone/dealer'), name: 'dealer', meta: { title: '课程管理', isTab: true } },
    // 体检管理-新增
    { path: '/add_examination', component: _import('examination/add_examination'), name: 'add_examination', meta: { title: '体检管理-新增', isTab: true } },
    // 体检管理-详情
    { path: '/taxinfo', component: _import('examination/taxinfo'), name: 'taxinfo', meta: { title: '体检管理-详情', isTab: true } },
    // 会员管理
    { path: '/personage', component: _import('member/personage'), name: 'personage', meta: { title: '个人管理', isTab: true } },
    { path: '/business', component: _import('member/business'), name: 'business', meta: { title: '项目企业', isTab: true } },
    { path: '/distributor', component: _import('member/distributor'), name: 'distributor', meta: { title: '经销商管理', isTab: true } },
    { path: '/tax', component: _import('member/tax'), name: 'tax', meta: { title: '税务系统管理', isTab: true } },
    // 用工轨迹
    { path: '/swj-recruitment', component: _import('member/recruitment'), name: 'swj-recruitment', meta: { title: '用工轨迹', isTab: true } },
    { path: '/swj-salary', component: _import('member/compensation'), name: 'swj-salary', meta: { title: '轨迹详情', isTab: true } },
    // 体检管理
    { path: '/examination', component: _import('examination/recruitment'), name: 'examination', meta: { title: '体检管理', isTab: true } },
    // 课程管理
    { path: '/curriculum', component: _import('alone/compensation'), name: 'curriculum', meta: { title: '课程管理', isTab: true } },
    // 体质管理
    { path: '/tice', component: _import('constitution/revenue'), name: 'tice', meta: { title: '体质管理', isTab: true } },
    // 体质管理-新增
    { path: '/sys-bill', component: _import('constitution/invoice'), name: 'sys-bill', meta: { title: '体质管理-新增', isTab: true } },
    // 体质管理-详情
    { path: '/constitution_details', component: _import('constitution/constitution_details'), name: 'constitution_details', meta: { title: '体质管理-修改', isTab: true } },
    // 新需求
    // 任务管理
    { path: '/sys-task', component: _import('newDemand/task'), name: 'sys-task', meta: { title: '任务管理', isTab: true } },
    // 作业管理
    { path: '/commission_default', component: _import('alone/commission'), name: 'commission_default', meta: { title: '作业管理', isTab: true } },
    //  作业管理 作业详情
    { path: '/commission_details', component: _import('work_management/work_details'), name: 'commission_details', meta: { title: '作业详情', isTab: true } },
    { path: '/dietddd', component: _import('consultative/indivagre'), name: 'dietddd', meta: { title: 'dsad ', isTab: true } },
    { path: '/privacy', component: _import('consultative/privacy'), name: 'privacy', meta: { title: '隐私协议', isTab: true } },
    // 合同管理
    { path: '/contract', component: _import('newDemand/contract'), name: 'contract', meta: { title: '合同管理', isTab: true } },
    // 系统管理
    { path: '/sys-role', component: _import('system/rights'), name: 'sys-role', meta: { title: '权限管理', isTab: true } },
    // 用户管理
    { path: '/user-setting', component: _import('system/account'), name: 'user-setting', meta: { title: '用户管理', isTab: true } },
    { path: '/user-add', component: _import('system/homeImg'), name: 'user-add', meta: { title: '用户管理-新增', isTab: true } },
    { path: '/sys-log', component: _import('system/operlog'), name: 'sys-log', meta: { title: '操作日志', isTab: true } },
    { path: '/sys-wxbanner', component: _import('modules/sys/wxbanner'), name: 'sys-wxbanner', meta: { title: '轮播图', isTab: true } },
    { path: '/othersettings', component: _import('system/othersettings'), name: 'othersettings', meta: { title: '其他设置', isTab: true } },
    //  推荐课程
    { path: '/course-recommen', component: _import('recommend_class/index'), name: 'course-recommen', meta: { title: '推荐课程', isTab: true } },
    // 硬件管理
    { path: '/hardware', component: _import('hardware_admin/index'), name: 'hardware', meta: { title: '硬件管理', isTab: true } },
    //健康报告health_report
    { path: '/healthy', component: _import('health_report/index'), name: 'healthy', meta: { title: '健康报告', isTab: true } },
    // 上传成绩up_results
    { path: '/exam', component: _import('up_results/index'), name: 'exam', meta: { title: '上传成绩', isTab: true } },
    // 饮食管理
    { path: '/diet', component: _import('food_admin/index'), name: 'diet', meta: { title: '饮食管理', isTab: true } },
    // 新增硬件add_health
    { path: '/add_health', component: _import('hardware_admin/add_health'), name: 'add_health', meta: { title: '新增硬件', isTab: true } },
    // 录入菜单 input_menu
    { path: '/input_menu', component: _import('food_admin/input_menu'), name: 'input_menu', meta: { title: '录入菜单', isTab: true } },
    // 作息管理
    { path: '/work-rest', component: _import('workRest/index'), name: 'work-rest', meta: { title: '作息管理', isTab: true } },
    // 课程训练 class_train
    { path: '/class_train', component: _import('class_train/index'), name: 'class_train', meta: { title: '课程训练', isTab: true } },
    // 课程训练——协调
    { path: '/train_coordinate', component: _import('class_train/train_coordinate'), name: 'train_coordinate', meta: { title: '课程训练-协调', isTab: true } },
    //课程训练-协调-详情train_coordinate_details
    { path: '/train_coordinate_details', component: _import('class_train/train_coordinate_details'), name: 'train_coordinate_details', meta: { title: '课程训练-协调-详情', isTab: true } },
    //作业管理-默认页面commission_default
    { path: '/homework', component: _import('alone/commission_default'), name: 'homework', meta: { title: '作业管理-默认', isTab: true } },
    //考试管理exam
    { path: '/achieventment', component: _import('exam_admin/exam'), name: 'achieventment', meta: { title: '考试管理', isTab: true } },
    //考试管理-创建考试 creat_exam
    { path: '/creat_exam', component: _import('exam_admin/creat_exam'), name: 'creat_exam', meta: { title: '创建考试', isTab: true } },
    //考试管理-考试详情 exam_details
    { path: '/exam_details', component: _import('exam_admin/exam_details'), name: 'exam_details', meta: { title: '考试详情', isTab: true } },



  ],
  beforeEnter(to, from, next) {
    // 没用token清空登录信息，跳转登录页码面
    // let token = Vue.cookie.get('token')
    let token = JSON.parse(sessionStorage.getItem('token'))
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      next({ name: 'login' })
      // next()
    }
    next()
  }
}

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes)
})

// 前置守卫
router.beforeEach((to, from, next) => {
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  // ￥￥￥￥请求获取的菜单列表
  if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
    next()
  } else {
    http({
      url: http.userUrl('getOpenMenuTreeList'),
      method: 'get',
      params: {
        token: JSON.parse(sessionStorage.getItem('token')),
        model: 'sports'
      }
    }).then(({ data }) => {
      console.log('请求获取的路由信息是什么:', data)
      if (data && data.errorCode === '0') {

        var arr = data.data[0].children;
        for (const i in arr) {
          arr[i].menuId = arr[i].id;
          arr[i].is_default = 0;
          if (sessionStorage.getItem('menuList')) {
            const brr = JSON.parse(sessionStorage.getItem('menuList'))
            for (let j = 0; j < brr.length; j++) {
              if (brr[j].is_default == 1) {
                arr[j].is_default = 1
              }
            }
          } else {
            arr[0].is_default = 1;
          }
          for (const j in arr[i].children) {
            arr[i].children[j].menuId = arr[i].children[j].id
          }
        }
        console.log('dasds', arr);
        fnAddDynamicMenuRoutes(arr)
        router.options.isAddDynamicMenuRoutes = true
        sessionStorage.setItem('menuList', JSON.stringify(arr || '[]'))
        // sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
        next({ ...to, replace: true })
      } else {
        sessionStorage.setItem('menuList', '[]')
        // sessionStorage.setItem('permissions', '[]')
        next()
      }
    }).catch((e) => {
      console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
      router.push({ name: 'login' })
      // next()
    })
  }
})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
  var temp = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      var route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        try {
          route['component'] = _import(`modules/${menuList[i].url}`) || null
        } catch (e) { }
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    router.addRoutes([
      mainRoutes,
      { path: '*', redirect: { name: '404' } }
    ])
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
    // console.log('\n')
    // console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    // console.log(mainRoutes.children)
    // console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}

export default router
